TARGET = links

C_SOURCES =  src/main.c \
src/uart.c \
src/led.c

C_INCLUDES = -Iinc

ASM_SOURCES = start.s

CPU = -mcpu=cortex-m3
MCU = $(CPU) -mthumb

CFLAGS = -c -g $(MCU) -Wall $(C_INCLUDES) -fno-builtin

PREFIX = arm-none-eabi-
CC = $(PREFIX)gcc
AS = $(PREFIX)gcc -x assembler-with-cpp
LD=$(PREFIX)ld
CP = $(PREFIX)objcopy
SZ = $(PREFIX)size
OBJDUMP=$(PREFIX)objdump
HEX = $(CP) -O ihex
BIN = $(CP) -O binary -S

BUILD_DIR = build

OBJECTS = $(addprefix $(BUILD_DIR)/,$(notdir $(ASM_SOURCES:.s=.o)))
vpath %.s $(sort $(dir $(ASM_SOURCES)))
OBJECTS += $(addprefix $(BUILD_DIR)/,$(notdir $(C_SOURCES:.c=.o)))
vpath %.c $(sort $(dir $(C_SOURCES)))


all : $(BUILD_DIR)/$(TARGET).elf $(BUILD_DIR)/$(TARGET).hex $(BUILD_DIR)/$(TARGET).bin $(BUILD_DIR)/$(TARGET).dis
	$(SZ) $<

$(BUILD_DIR)/%.o: %.c | $(BUILD_DIR)
	$(CC) $(CFLAGS)  $< -o $@ -MMD -MP -MF"$(@:%.o=%.d)"

$(BUILD_DIR)/%.o: %.s | $(BUILD_DIR)
	$(AS) $(CFLAGS)  $< -o $@

$(BUILD_DIR)/$(TARGET).elf: $(OBJECTS) | $(BUILD_DIR)
	$(LD) -g $(OBJECTS) -T stm32f103zet6.ld -o $@

$(BUILD_DIR)/%.hex: $(BUILD_DIR)/%.elf | $(BUILD_DIR)
	$(HEX) $< $@
	
$(BUILD_DIR)/%.bin: $(BUILD_DIR)/%.elf | $(BUILD_DIR)
	$(BIN) $< $@

$(BUILD_DIR)/%.dis: $(BUILD_DIR)/%.elf
	$(OBJDUMP) -D -m cortex-m3 $< > $@

$(BUILD_DIR):
	mkdir $@

-include $(wildcard $(BUILD_DIR)/*.d)

clean:
	rm -rf $(BUILD_DIR)
